
let vs = 0;
let renameIndex = 0;
$(function(){

	websocket();

	getList("/fileList",{
		"path":null,
		"closeOrRefund":0
	},0);

	document.onkeydown = function HandleTabKey(evt) {

		var theEvent = evt || window.event;
		/**
		 * 回车输入
		 */
		if((theEvent.keyCode || theEvent.which || theEvent.charCode) == 13){

			// 命令行的输入
			if(inputState('order')){
				if($('#order').val() === "clear"){
					$('.nav_ul').empty();
					$('#order').val("");
				}else if ($('#order').val() === "add btnPath") {
					addBtnPath(0);
				}else if($('#order').val() === "add btnPath -b"){
					addBtnPath(1);
				}else {
					$.get('/sendTheCommand',{
						order:$('#order').val()
					},function (res){
						if (res.code === '200'){
							getList("/fileList",{
								"path":null,
								"closeOrRefund":0
							},0);
							$('#order').val("");
						}else {
							println(res);
						}
					});
				}
			}

			// 文本路径的输入
			if (inputState('inputPath')){
				getList("/fileList",{
					"path":$('#inputPath').val(),
					"closeOrRefund":2
				},0);

			}

		}
	}

	layui.use(['form', 'layer','upload'], function () {
		var layer = layui.layer,form = layer.form,upload = layui.upload;
		/**
		 * 重命名弹出层
		 */
		$("#fileRename").click(function () {
			let oldName = $('#font'+vs).text();
			menuNone("none");
			renameIndex =  layer.open({
				type: 1,
				title:"重命名",
				area: ['300px', '220px'],
				content: '<div class="layui-row"><div class="layui-col-md12"><div class="layui-form-item"style="margin-top: 10px;padding-left: 10px;padding-right: 10px;"><input type="text" name="oldFileName" value='+oldName+' disabled id="oldFileName"autocomplete="off"class="layui-input"></div><div class="layui-form-item"style="padding-left: 10px;padding-right: 10px;"><input type="text"name="newFileName"id="newFileName"lay-verify="required"lay-reqtext="不能为空"placeholder="新名称 (需要加后缀)"autocomplete="off"class="layui-input"></div><div class="layui-form-item"style="padding-left: 10px;padding-right: 10px;"><button type="button" style="width: 100%;"class="layui-btn" onclick="rename()" >立即提交</button></div></div></div>'
			});
			return false;
		});

		/**
		 * 文件上传
		 */
		let upi;
		upload.render({
			elem: '#btnImport' //绑定元素
			, url: '/upload' //上传接口
			, accept: 'file'
			, exts: $('#suffix').val()
			, before: function () {
				upi = layer.msg('上传中...', { icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, offset: '50%', time: 300000 });
			}
			, done: function (res) {
				if (res.code == 200){
					layer.close(upi);
				}else{
					layer.close(upi);
					layer.msg(res.msg, {icon: 5});
				}
				getList("/fileList",{
					"path":null,
					"closeOrRefund":0
				},0);
			}
		});


		/**
		 * 路径的输入
		 * @type {string}
		 */
		$('#badgePath').click(function () {
			$('#badgePath').hide();
			$('#inputPath').show();
			$('#inputPath').val($('#currentDirectory').text());
			$('#inputPath').focus();
			return false;
		})
		$('#inputPath').click(function () {
			return false;
		})
		document.onclick = function(){
			$('#inputPath').hide();
			$('#badgePath').show();
		}
		
		/**
		 * 文件属性
		 * 当点击属性的时候才去根据名称查询
		 * 不会刚刚开始一次性全部查出来，
		 */
		$("#fileAttribute").click(function () {
			let fileName = $('#font'+vs).text();
			let filePath = $('#currentDirectory').text()+"/"+fileName;
			let data = {
				"path":filePath,
				"closeOrRefund":null
			}
			menuNone("none");
			$.ajax({
				url:"/fileSizeAndAuthority",
				method:'post',
				data:JSON.stringify(data),
				dataType:'JSON',
				contentType: "application/json; charset=utf-8",
				success:function (res){
					println(res);
					layer.open({
						type: 1,
						title:"属性",
						area: ['300px', '228px'],
						content: '<div class="layui-row"><div class="layui-col-md12"><table class="layui-table"><tbody><tr><td style="width: 116px;">文件名称</td><td style="width: 182px;word-wrap:break-word;">'+fileName+'</td></tr><tr><td style="width: 116px;">文件路径</td><td style="width: 182px;word-wrap:break-word;">'+filePath+'</td></tr><tr><td style="width: 116px;">文件大小</td><td style="width: 182px;word-wrap:break-word;">'+filterSize(res.data.fileSize)+'</td></tr><tr><td style="width: 116px;">文件权限</td><td style="width: 182px;word-wrap:break-word;">'+res.data.authority+'</td></tr></tbody></table></div></div>'
					});
				},
				error:function (data){

				}
			});

			return false;
		});

		/**
		 * 文件删除
		 */
		$('#fileDelete').click(function (){
			menuNone("none");
			//询问框
			layer.confirm('确定删除当前文件吗？', {
				btn: ['确定','取消'] //按钮
			}, function(){
				let fileName = $('#font'+vs).text();
				let filePath = $('#currentDirectory').text();
				$.get("/fileDelete",{
					filePath:filePath,
					fileName:fileName
				},function (res){
					println(res);
					getList("/fileList",{
						"path":null,
						"closeOrRefund":0
					},0);
				});

			});
		});


		/**
		 * 查看命令
		 */
		$('#selectCommand').click(function (){
			layer.open({
				type: 2
				,area: ['1250px', '550px']
				,fixed: false
				,title:'命令大全'
				,content: $('#requestUrl').val()+"/commandView"
				,btn: '关闭'
				,btnAlign: 'c' //按钮居中
			});

		});



	});




	/**
	 * 关闭菜单项
	 */
	$('.show-div').click(function(){
		menuNone("none");
	});

});

/**
 * 添加按钮路径
 */
function addBtnPath(num) {
	let obj = {
		"id":"btn"+new Date().getTime()+"and"+$('#principalHost').text(),
		"btnPath":$('#currentDirectory').text()
	}
	if(/[\u4E00-\u9FA5]/g.test($('#currentDirectory').text())){
		layer.msg("检测到包含中文目录", {icon: 5});
		return;
	}
	obj.showId = num;
	obj.btnPath = obj.btnPath.replaceAll('/','$');
	let str = JSON.stringify(obj);
	indexGetCookie("jsonAndCookie") == "true"?
		$.ajax({
			url:'/addBtnObj',
			method:'post',
			data:str,
			dataType:'JSON',
			contentType: "application/json; charset=utf-8",
			success:function (res) {
			}
		})
		:indexSetCookie(obj.id,str,"d30");

	location.reload();
}

/**
 * 更改后缀名
 */
function rename(){
	let path = $('#currentDirectory').text()+"/";
	let oldName = $('#oldFileName').val();
	let newName = $('#newFileName').val();
	if (newName.indexOf(".") === -1){
		layer.msg("必须带后缀");
	}else {
		$.get("/rename",{
			oldPath:path+oldName,
			newPath:path+newName
		},function (res){
			layer.close(renameIndex);
			println(res);
			getList("/fileList",{
				"path":null,
				"closeOrRefund":0
			},0);
		});
	}
}


/**
 * 判断文本框是否获取焦点
 */
function inputState(id){
	var order = document.getElementById(id);
	if(order == document.activeElement){
		return true;
	}
	return false;
}

function getList(url,data,bol){
	layui.use("layer", function () {

		let i;
		$.ajax({
			url:url,
			method:'post',
			data:JSON.stringify(data),
			dataType:'JSON',
			contentType: "application/json; charset=utf-8",
			beforeSend:function (){
				i = layer.msg('努力中...', { icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, offset: '50%', time: 8000 });
					setTimeout(function () {
						if ($('#dataList').children().length <=0){
							i = layer.msg('<span style="color: red;">[异常]</span>&nbsp;<a href="/index">重新加载页面</a>', { icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, offset: '50%', time: 30000 });
						}
					},8000);


			},
			success:function (res){
					if (bol === 0){
						show_data(res);
					}
				layer.close(i);
			},
			error:function (data){

			}
		});

	});
}

function println(res){
	debugMsg(res,res.msg);
}
function debugMsg(res,msg){
	if(!$('#errMsg').hasClass("layui-badge")){
		$('#errMsg').addClass("layui-badge")
	}

	$('#errMsg').text(res.code === "200"?"正常":"异常");
	if ($('#errMsg').text() === "正常"){
		info(res.date,msg,true);
		$('#errMsg').addClass("layui-bg-green");
	}else {
		info(res.date,msg,false);
		$('#errMsg').removeClass("layui-bg-green");
	}
}
function info(date,msg,b){
	if (msg !== "" && msg !== null){
		let m = b?msg:"<span style='color: red;'>"+msg+"</span>";
		$("<li class='nav_li'>[INFO "+date+"]&nbsp;&nbsp; "+m+"</li>").appendTo('.nav_ul');
		($('.nav_ul').children("li:last-child")[0]).scrollIntoView();
	}
}

function show_data(res){
	println(res);
	$('#dataList').empty();
	let list =  res.data.listPath;
	if (list !==null || list !== ""){
		$.each(list,function (index,item){
			let titleName = item.isDir === 1?'双击进入'+item.fileName+'目录':'双击预览'+item.fileName+'文件';
			let div = '<div oncontextmenu="fielDown('+index+','+item.isDir+',this)" title="'+titleName+'" ondblclick="fileBtn('+index+','+item.isDir+')" class="file" dc="'+index+'"isDir="'+item.isDir+'"><div class="file-img"><img src="'+(item.isDir==1?"/images/fileDir.png":"/images/doucment.png")+'"></div><div id="font'+index+'"class="file-font">'+item.fileName+'</div></div>';
			$('#dataList').append(div);
		});
		$('#dataList').append('<div style="width: 100%;height: 75px;float: left;"></div>');
		$('#currentDirectory').text(lastCheckPath(res.data.currentDirectory));

	}
}

/**
 * 文件双击事件
 * @param val
 * @param dir
 */
function fileBtn(val,dir){
	var fileName = $('#font'+val).text();
	menuNone("none");
	if(dir === 0){
		let windowObj = window.parent.open($('#requestUrl').val()+"/fileView?fileName="+fileName);
		windowObj.onload=function(){
			windowObj.document.title = fileName + '文件正在预览';
		}
	}else {
		getList("/fileList",{
			"path":"/"+fileName,
			"closeOrRefund":0
		},0);
	}
}

/**
 * 右键事件
 */
function fielDown(index,dir){
	if(dir === 0){
		$('#menu').css("left",this.event.clientX+"px");
		$('#menu').css("top",(this.event.clientY-123)+"px");
		vs = index;
		menuNone("block");
	}else{
		menuNone("none");
	}
}

/**
 * 返回路径
 */
function route(path,index){
	getList("/fileList",{
		"path":path,
		"closeOrRefund":index
	},0);
}


/**
 * 下载文件
 */
function down(){
	info("be downloading","文件下载中...");
	layui.use("layer", function () {
		menuNone("none");
		let i;
		$.get('/download',{
			path:$('#currentDirectory').text(),
			fileName:$('#font'+vs).text()
		},function (res){
			println(res);
		});
	});
}

function filterSize(size) {
	if (!size) return '';
	if (size < pow1024(1)) return size + ' B';
	if (size < pow1024(2)) return (size / pow1024(1)).toFixed(2) + ' KB';
	if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2) + ' MB';
	if (size < pow1024(4)) return (size / pow1024(3)).toFixed(2) + ' GB';
	return (size / pow1024(4)).toFixed(2) + ' TB'
}

// 求次幂
function pow1024(num) {
	return Math.pow(1024, num)
}

function lastCheckPath(path){
	path = path.replace("//","/");
	if (path.length >= 2){
		let newPath = path.substring(path.length-1);
		if ("/" === newPath){
			return path.substring(0,path.length-1);
		}
	}
	return path;
}


function menuNone(state){
	$('#menu').css("display",state);
}

function websocket() {
	let websocket = null;
	if ('WebSocket' in window){
		websocket = new WebSocket("ws://"+$('#webSocketHostPort').val()+"/webSocket");
	}else {
		console.log("不支持websocket");
	}
	websocket.onopen = function (e) {
		console.log("建立连接")
	}
	websocket.onclose = function (e) {
		console.log("连接关闭");
	}
	websocket.onmessage = function (e) {
		$('#connectCount').text(e.data);
	}
	websocket.onerror = function () {
		console.log("websocket 通信发生错误")
	}
}

function indexSetCookie(name,value,time){
	var strsec = getsec(time);
	var exp = new Date();
	exp.setTime(exp.getTime() + strsec*1);
	document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function indexGetCookie(name){
	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	if(arr=document.cookie.match(reg)) return unescape(arr[2]);
	else return null;
}
function getsec(str){
	var str1=str.substring(1,str.length)*1;
	var str2=str.substring(0,1);
	if (str2=="s")	{
		return str1*1000;
	}
	else if (str2=="h")	{
		return str1*60*60*1000;
	}
	else if (str2=="d")	{
		return str1*24*60*60*1000;
	}
}
